package codingInterview.leetcode.editor.cn;

//给定一棵二叉搜索树，请找出其中第 k 大的节点的值。 
//
// 
//
// 示例 1: 
//
// 
//输入: root = [3,1,4,null,2], k = 1
//   3
//  / \
// 1   4
//  \
//   2
//输出: 4 
//
// 示例 2: 
//
// 
//输入: root = [5,3,6,2,4,null,null,1], k = 3
//       5
//      / \
//     3   6
//    / \
//   2   4
//  /
// 1
//输出: 4 
//
// 
//
// 限制： 
//
// 
// 1 ≤ k ≤ 二叉搜索树元素个数 
// 
// Related Topics 树 深度优先搜索 二叉搜索树 二叉树 👍 270 👎 0

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;

//Java：剑指 Offer 54 - 二叉搜索树的第k大节点
public class ErChaSouSuoShuDeDiKdaJieDianLcof{
    public static void main(String[] args) {
                Solution solution = new ErChaSouSuoShuDeDiKdaJieDianLcof().new Solution();
        // TO TEST
    }
    
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int k;
    public int kthLargest(TreeNode root, int k) {
        this.k =k;
        return dfs(root).val;
    }

    public TreeNode dfs(TreeNode root){
        if(root==null) return null;
        TreeNode target = null;
        if (target ==null)
            target = dfs(root.right);
        if(target == null){
            if(k==1) target =root;
            k--;
        }
        if(target == null)
            target = dfs(root.left);
        return target;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
}
